package handler

import (
	"fmt"
	"gitee.com/simple-set/simple.proxy/src/utils"
	"io"
	"log/slog"
	"strings"
)

type AuthUser struct {
	users    map[string]string
	userFile string
}

func NewAuthUser() *AuthUser {
	return &AuthUser{users: make(map[string]string)}
}

func (a *AuthUser) AddUser(user, pass string) {
	a.users[strings.TrimSpace(user)] = strings.TrimSpace(pass)
}

func (a *AuthUser) LoadUser(fileName string) {
	a.userFile = fileName
	fileCache, err := utils.NewFileCache(fileName)
	if err != nil {
		slog.Error(fmt.Sprintf("%s LoadUser exception %s", fileName, err.Error()))
		return
	}
	defer fileCache.Close()

	for {
		line, err := fileCache.ReadLine()
		if err == io.EOF {
			break
		}
		if err != nil {
			slog.Error(fmt.Sprintf("%s LoadUser exception %s", fileName, err.Error()))
			break
		}
		if strings.HasPrefix(strings.TrimSpace(line), "#") {
			continue
		}
		if strings.TrimSpace(line) == "" {
			continue
		}
		if user, passwd, ok := strings.Cut(line, ":"); ok {
			a.AddUser(user, passwd)
		}
	}
}

func (a *AuthUser) Challenge(user, pass string) bool {
	if user == "" || pass == "" {
		return false
	}
	return a.users[user] == pass
}
